'''Gets non-Chromebook notes and parts for a warranty claim.'''
import PySimpleGUI as sg
from warranty_manager.claim.common import SUBMIT_COLOR, CANCEL_COLOR
from warranty_manager.gui.validation import validate_notes
from warranty_manager.gui.validation import validate_part_numbers


def get_num(info_type):
    '''
    Gets a number, to use to determine the number of notes and parts
    for a given warranty claim.
    '''
    num = 0

    layout = [
        [sg.Text('Please enter a number:'), sg.InputText(key='-NUM-', size=(5, 1))],
        [sg.Submit(button_color=SUBMIT_COLOR), sg.Cancel(button_color=CANCEL_COLOR)]
    ]

    window = sg.Window('Get Number', layout)

    while True:
        event, values = window.read()

        if event in (None, 'Cancel'):
            break
        elif event == 'Submit':
            try:
                num = int(values['-NUM-'])
            except ValueError:
                sg.popup('You must enter a number.', title='Error')
                window['-NUM-'].update('')
                continue
            else:
                if 1 <= num <= 5:
                    break
                else:
                    sg.popup(
                        'You must enter a number between one and five.',
                        title='Error'
                    )
                    window['-NUM-'].update('')
                    continue
        else:
            continue

    window.close()
    return num


def select_part(part_nums):
    '''Selects a part number from a list of parts.'''
    part_num = None

    layout = [
        [
            sg.Listbox(
                values=tuple(part_nums),
                size=( 25, len(part_nums) ),
                key='-PART_NUM-'
            )
        ],
        [
            sg.Submit(button_color=SUBMIT_COLOR),
            sg.Cancel(button_color=CANCEL_COLOR)
        ]
    ]

    window = sg.Window('Part Selector', layout)

    values = window.read()[1]

    try:
        part_num = values['-PART_NUM-'][0]
    except IndexError:
        return None
    else:
        return part_num
    finally:
        window.close()


def get_part_nums_gui():
    '''Gets a list of part numbers to add to the CSN warranty claim.'''
    num_parts = get_num('part numbers')

    if num_parts:
        part_nums = set()
        layout = []

        for i in range(1, num_parts + 1):
            part_nums_layout = [sg.Text(f"Part #{i}")]
            part_nums_layout.append(
                sg.Input( key=f'-PART_NUM_{i}-', size=(10, 1) )
            )
            layout.append(part_nums_layout)

        layout.append([
            sg.Button('Add Part Number(s)', button_color=SUBMIT_COLOR),
            sg.Cancel(button_color=CANCEL_COLOR)
        ])

        window = sg.Window('Part Numbers List', layout)

        while True:
            event, values = window.read()

            if event in (None, 'Cancel'):
                break
            elif event == 'Add Part Number(s)':
                validated_part_nums = validate_part_numbers(values)

                if validated_part_nums:
                    part_nums.update(validated_part_nums)
                    break

                sg.popup_error(
                    'You have entered one or more invalid part numbers. '
                    'Please try again.',
                    title='Error Message'
                )
            else:
                continue

        window.close()
        return part_nums
    else:
        return set()


def get_notes_gui():
    '''Gets a list of non-Chromebook CSN notes to add to the warranty claim.'''
    num_notes = get_num('notes')

    if num_notes:
        notes = set()
        layout = []

        for i in range(1, num_notes + 1):
            notes_layout = [sg.Text(f"Note #{i}")]
            notes_layout.append(
                sg.MLine( key=f'-NOTE_NUM_{i}-', size=(50, 5) )
            )
            layout.append(notes_layout)

        layout.append([
            sg.Button('Add Note(s)', button_color=SUBMIT_COLOR),
            sg.Cancel(button_color=CANCEL_COLOR)
        ])

        window = sg.Window('Notes List', layout)

        while True:
            event, values = window.read()

            if event in (None, 'Cancel'):
                break
            elif event == 'Add Note(s)':
                validated_notes = validate_notes(values)

                if validated_notes:
                    notes.update(validated_notes)
                    break

                sg.popup_error(
                    'You have not entered a note into one or more fields. '
                    'Please try again.',
                    title='Error Message'
                )
            else:
                continue

        window.close()
        return notes
    else:
        return set()
